package encryption;


import java.security.MessageDigest;

import javax.crypto.*;
import javax.crypto.spec.*;

public class Encryption {

	private SecretKeySpec skeySpec;
	private Cipher cipher;
	
	public Encryption(String passphrase) throws Exception{
		
		//creates MD5 hash of passphrase
		byte[] bytesOfMessage = passphrase.getBytes("UTF-8");
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] thedigest = md.digest(bytesOfMessage);
		
		//creates key using hash digest
		skeySpec = new SecretKeySpec(thedigest, "AES");
		
		//creates accomplanying cipher
		cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	}
	
	public byte[] encrypt (byte[] plaintext) throws Exception{
		//returns byte array encrypted with key
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		
		byte[] ciphertext =	cipher.doFinal(plaintext);
		
		if (ciphertext.length>1500){
			System.err.println("Packet length: "+ciphertext.length+ " too big");
		}
		
		return ciphertext;
	}
	
	public byte[] decrypt (byte[] ciphertext) throws Exception{
		//returns byte array decrypted with key
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		
		byte[] plaintext = cipher.doFinal(ciphertext);
		
		return plaintext;
	}
}